package com.browser.download;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Data
public class DownloadTask implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(DownloadTask.class);
    
    private final String id;
    private final String url;
    private final String targetPath;
    private volatile DownloadStatus status;
    private volatile long bytesDownloaded;
    private volatile long totalBytes;
    private volatile boolean isPaused;
    private volatile boolean isCancelled;

    public DownloadTask(String url, String targetPath) {
        this.id = UUID.randomUUID().toString();
        this.url = url;
        this.targetPath = targetPath;
        this.status = DownloadStatus.PENDING;
    }

    @Override
    public void run() {
        try {
            status = DownloadStatus.DOWNLOADING;
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            totalBytes = connection.getContentLengthLong();

            try (InputStream in = connection.getInputStream();
                 FileOutputStream out = new FileOutputStream(targetPath)) {

                byte[] buffer = new byte[8192];
                int count;

                while ((count = in.read(buffer)) > 0 && !isCancelled) {
                    if (!isPaused) {
                        out.write(buffer, 0, count);
                        bytesDownloaded += count;
                    } else {
                        Thread.sleep(100);
                    }
                }

                if (isCancelled) {
                    status = DownloadStatus.CANCELLED;
                } else {
                    status = DownloadStatus.COMPLETED;
                }
            }
        } catch (Exception e) {
            logger.error("Download failed: {}", url, e);
            status = DownloadStatus.FAILED;
        }
    }

    public void pause() {
        isPaused = true;
        status = DownloadStatus.PAUSED;
    }

    public void resume() {
        isPaused = false;
        status = DownloadStatus.DOWNLOADING;
    }

    public void cancel() {
        isCancelled = true;
    }

    public String getId() {
        return id;
    }

    public DownloadStatus getStatus() {
        return status;
    }

    public double getProgress() {
        return totalBytes > 0 ? (double) bytesDownloaded / totalBytes : 0;
    }
} 